package com.am.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.am.server.json.JsonUtil;
import com.chenlb.mmseg4j.ComplexSeg;
import com.chenlb.mmseg4j.Dictionary;
import com.chenlb.mmseg4j.MMSeg;
import com.chenlb.mmseg4j.Seg;
import com.chenlb.mmseg4j.Word;

public class WordSplitServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected Dictionary dic;

	public WordSplitServlet() {
		super();
		dic = Dictionary.getInstance();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html; charset=utf-8");
		String sentence = req.getParameter("s");
		PrintWriter out = resp.getWriter();
		List<String> words = Collections.emptyList();
		if (sentence != null && sentence.length() > 0) {
			words = segWords(new StringReader(sentence));
		}
		out.println(JsonUtil.strings2Json(words));
		out.flush();
	}

	protected Seg getSeg() {
		return new ComplexSeg(dic);
	}

	public List<String> segWords(Reader input) throws IOException {
		List<String> rets = new ArrayList<String>();
		Seg seg = getSeg(); // 取得不同的分词具体算法
		MMSeg mmSeg = new MMSeg(input, seg);
		Word word = null;
		while ((word = mmSeg.next()) != null) {
			String w = word.getString();
			rets.add(w);
		}
		return rets;
	}
}
